const Service = require('egg').Service;
const { substring, parseTime } = require('../utils/index');
const { writeFile } = require('../common/file');
const { addFileRedis, removeFile, getFileRedis, removeFileRedis } = require('../common/file');
const { v4: uuidv4 } = require('uuid');
const path = require('path');

class FileService extends Service {
  async uploadFile(file, fileInfo) {
    const newFileInfo = JSON.parse(JSON.stringify(fileInfo));
    for (const label in fileInfo) {
      if (label != 'fileName') {
        fileInfo[label] = substring(fileInfo[label], 0, 8);
      }
    }
    const fileId = uuidv4();
    const { fileName, schoolId, shopId, openId } = fileInfo;
    const newFileName = `${schoolId}${shopId}${openId}${fileId.substring(0, 8)}${fileName}`;
    const viewPath = `/public/uploads/${schoolId}/${shopId}/${newFileName}`;
    const basePath = path.join(__dirname, '../', 'public/uploads', schoolId, shopId);
    const target = path.resolve(basePath, newFileName);
    const { status, msg } = await writeFile(file.filepath, target);
    const obj = {
      file_name: newFileName,
      file_id: fileId,
      school_id: newFileInfo.schoolId,
      shop_id: newFileInfo.shopId,
      open_id: newFileInfo.openId,
      view_path: viewPath,
      upload_time: parseTime(new Date()),
      order_id: null
    }
    //发起存储
    await addFileRedis(fileId, obj, this.app);
    if (!status) {
      return { code: 200, msg, status: 'failure' }
    } else {
      return { code: 200, msg, status: 'success', data: { ...obj } }
    }
  }
  async deleteFile(fileId) {
    const file = await getFileRedis(fileId, this.app);
    const res = removeFile(file.view_path);
    if (res) {
      await removeFileRedis(fileId, this.app);
      return { code: 200, msg: '', status: 'success', data: { ...file } }
    } else {
      return { code: 400, msg: '删除文件失败', status: 'failure' }
    }
  }
}

module.exports = FileService;